package com.next.aappublicapp;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.Toast;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.google.analytics.tracking.android.EasyTracker;
import com.next.aappublicapp.util.FacebookUtil;
import com.next.aappublicapp.util.GcmUtil;
import com.next.aappublicapp.util.UserProfileUtil;

public class LoginActivity extends BaseActivity {

	
	private Session.StatusCallback statusCallback = new SessionStatusCallback();
	//private ImageButton facebookLoginButton;
	private LoginButton loginButton;
	private ImageButton twitterButton;
	private ImageButton skipButton;
	private boolean alreadyStartedMainActivity = false;
	private UiLifecycleHelper uiHelper;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		EasyTracker.getTracker().sendView("Login Screen");
		
		
		
		//make sure device is registered with google and our server
		GcmUtil.ensureDeviceIsRegistered(this);

		uiHelper = new UiLifecycleHelper(this, statusCallback);
	    uiHelper.onCreate(savedInstanceState);
	    
		setContentView(R.layout.activity_login);

		//Find all Widgets which we need
		loginButton = (LoginButton)findViewById(R.id.facebookLoginButton);
		
		//Now if user logged in then start Main Activity
		
        if(FacebookUtil.isFacebookLoggedIn()){
        	Log.i("Ravi", "Facebook is logged in");
            //Ok now it may be possible that use has saved profile but has not saved Facebook user ID
        	if(FacebookUtil.getFaceookUserId(this) == null){
        		Log.i("Ravi", "getFaceookUserId(this) is null");
        		startMainActivty(true);	
        	}else{
        		Log.i("Ravi", "getFaceookUserId(this) is NOT null");
        		startMainActivty(!UserProfileUtil.isUserProfiledSavedByUser(this));	
        	}
        	
        	return;
        }
		//loginButton.setPublishPermissions(Arrays.asList("publish_actions"));
		loginButton.setBackgroundResource(R.drawable.facebook_signin);
		loginButton.setWidth(getResources().getDrawable(R.drawable.facebook_signin).getBounds().width());
		loginButton.setHeight(getResources().getDrawable(R.drawable.facebook_signin).getBounds().height());
		//loginButton.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
		//loginButton.setReadPermissions(Arrays.asList("user_location", "user_birthday", "user_likes"));
		
		loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
            @Override
            public void onUserInfoFetched(GraphUser user) {
            	if(user != null){
            		Log.i("Ravi", "User Info Fetched "+user.getFirstName());	
            		EasyTracker.getTracker().sendEvent("Android", "Login", "FacebookLogin", 1L);
            	}else{
            		Log.i("Ravi", "User Info Fetched null");
            	}
            	
                // It's possible that we were waiting for this.user to be populated in order to post a
                // status update.
            }
        });
		
		twitterButton = (ImageButton)findViewById(R.id.twitterLoginButton);
		twitterButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				EasyTracker.getTracker().sendEvent("Android", "Login", "TwitterLogin", 1L);
				int duration = Toast.LENGTH_SHORT;
				Toast toast = Toast.makeText(LoginActivity.this, "Under Construction", duration);
				toast.show();	
				
			}
		});
		
		skipButton = (ImageButton)findViewById(R.id.skipLoginButton);
		skipButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				EasyTracker.getTracker().sendEvent("Android", "Login", "SkipLogin", 1L);
				startMainActivty(false);
			}
		});
		

	}
	@Override
	protected void onResume() {
		super.onResume();
		uiHelper.onResume();
		alreadyStartedMainActivity = false;
		Settings.publishInstallAsync(this, "179991405492511");
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}
	@Override
    public void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    public void onStop() {
        super.onStop();
        Session.getActiveSession().removeCallback(statusCallback);
        //EasyTracker.getInstance().activityStop(this);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("Ravi","onActivityResult = "+requestCode+","+resultCode+","+data);
        //Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
    }

	private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
        	Log.i("Ravi","SessionStatusCallback.call = "+state);
        	Log.i("Ravi","SessionStatusCallback.call = "+session.getAccessToken());
        	
            startMainActivityAfterFacebookLogin();
        }
    }
	
	private void startMainActivityAfterFacebookLogin() {
        Session session = Session.getActiveSession();
        Log.i("Ravi","startMainActivityAfterFacebookLogin updateView:session = "+session);
        if(Session.getActiveSession() != null && Session.getActiveSession().isOpened()){
        	if(FacebookUtil.getFaceookUserId(this) == null){
        		Log.i("Ravi", "startMainActivityAfterFacebookLogin getFaceookUserId(this) is null");
        		startMainActivty(true);	
        	}else{
        		Log.i("Ravi", "startMainActivityAfterFacebookLogin getFaceookUserId(this) is NOT null");
        		startMainActivty(!UserProfileUtil.isUserProfiledSavedByUser(this));	
        	}
        	//startMainActivty(!UserProfileUtil.isUserProfiledSavedByUser(this));
        }
        
        
        
    }
	private void startMainActivty(boolean goToRegistration){
		if(!alreadyStartedMainActivity){
			Log.i("Ravi", "alreadyStartedMainActivity : "+alreadyStartedMainActivity);
    		alreadyStartedMainActivity = true;
    		Log.i("Ravi", "goToRegistration "+goToRegistration);
        	//makeMeRequest(Session.getActiveSession());
    		if(goToRegistration){
    			Log.i("Ravi", "UserProfileActivity Starting "+goToRegistration);
        		Intent intent = new Intent(this,UserProfileActivity.class);
        		Bundle bundle = new Bundle();
        		intent.putExtra(PagerViewActivity.ARGS_BUNDLE, bundle);
        		this.startActivity(intent);
    		}else{
    			Log.i("Ravi", "Main Activity Starting "+goToRegistration);
    			Intent intent = new Intent(this,MainActivity.class);
        		Bundle bundle = new Bundle();
        		intent.putExtra(PagerViewActivity.ARGS_BUNDLE, bundle);
        		this.startActivity(intent);
    		}
    		finish();
    	}
	}
}

